﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using Common.Logging;
using Crawler.Reports;
using Crawler.Stuff;
using Crawler.VcontakteAPI;
using Quartz;
using System.Threading;

namespace Crawler.Job
{
    public class ParserJob : IStatefulJob, IInterruptableJob
    {
        private ILog log;
        private Thread currentThread;

        public ParserJob()
        {
            log = LogManager.GetCurrentClassLogger();
            log.Info("ParserJob Constructed");
        }

        #region IJob Members

        public void Execute(JobExecutionContext context)
        {
            var ctx = new VcontacteContext();
            try
            {
                bool ParseOrRepair = false;
                bool Growth = false;
                currentThread = Thread.CurrentThread;
                var last = ReportStore.Last();

                if (last != null && last.Report.StartDate.Day == DateTime.Now.Day) //сегодня
                {
                    if (!last.Report.IsSuccesfull && last.Report.Summary.Contains("Parsing")) //есть ошибки
                    {
                        ctx.SignIn();
                        ctx.RepairRequests(last.FailedReqests);
                        ParseOrRepair = true;
                    }
                    //else //ошибок нет
                    //{
                    //    ctx.Init();
                    //    ctx._reportStore.Report.Summary += "Nothing";
                    //    ctx._reportStore.Finish();
                    //}
                }
                else //не сегодня
                {
                    ctx.SignIn();
                    ctx.Parse();
                    ParseOrRepair = true;
                }
                if (!ParseOrRepair)
                {
                    log.Debug("prepare 4 growth");
                    var newlast = ReportStore.Last();

                    //Отработал и ошибок нет считаем рост
                    if (newlast != null && !newlast.Report.Summary.Contains("Nothing") &&
                        !newlast.Report.Summary.Contains("Growth") && newlast.Report.IsSuccesfull)
                    {
                        log.Debug("start calc growth");
                        var r = ReportStore.New("Growth");
                        var growths = new Growth().UpdateAppGrowth(DateTime.Now);
                        r.Report.NewApps = growths;
                        r.Finish();
                        Growth = true;
                    }
                    else
                    {
                        if (newlast == null)
                        {
                            log.Debug("can't calc growh, newlast is null");
                        }
                        else
                        {
                            log.DebugFormat("can't calc growth, newlast summary: {0}, IsSuccesfull: {1}",
                                            newlast.Report.Summary, newlast.Report.IsSuccesfull);
                        }
                    }
                }
                if (!Growth && !ParseOrRepair)
                {
                    ctx.Init();
                    ctx._reportStore.Report.Summary += "Nothing";
                    ctx._reportStore.Finish();
                }
            }
            catch (Exception e)
            {
                ctx._reportStore.Report.Summary += "Fail";
                ctx._reportStore.Finish();
                LogManager.GetCurrentClassLogger().ErrorFormat("Unhandled error. Type={0}, Message={1}, StackTrace={2}", e.GetType(), e.Message, e.StackTrace);
            }
            finally
            {
                ctx.Dispose();
            }
        }

        #endregion

        #region IInterruptableJob Members

        public void Interrupt()
        {
            currentThread.Abort();
        }

        #endregion
    }
}
